package com.yhk.wuchat.common.common.interceptor;

/**
 * @version 1.0
 * @Author moresuo
 * @Date 2024/4/8 15:31
 * @注释
 */

import cn.hutool.extra.servlet.ServletUtil;
import com.yhk.wuchat.common.common.domain.dto.RequestInfo;
import com.yhk.wuchat.common.common.util.RequestHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 专门收集信息的拦截器
 */
@Component
public class CollectorInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Long uid = Optional.ofNullable(request.getAttribute(TokenInterceptor.UID))
                .map(Object::toString)
                .map(Long::parseLong)
                .orElse(null);
        //获取用户ip
        String ip = ServletUtil.getClientIP(request);
        RequestInfo requestInfo=new RequestInfo();
        requestInfo.setUid(uid);
        requestInfo.setIp(ip);
        RequestHolder.set(requestInfo);
        return true;
    }

    /**
     * 将ThreadLocal中的内容清除，防止内存泄漏
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        RequestHolder.remove();
    }
}
